package com.icss.mqsp.db;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.icss.pangu.logging.Log;
import com.icss.pangu.logging.LogFactory;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

public class DBClient
{
  private static Log log = LogFactory.getLog(DBClient.class);
  private Map<String, SqlMapClient> sqlMapClientPool = new HashMap();
  
  public static DBClient getInstance()
  {
    return dbConnect;
  }
  
  public SqlMapClient getSqlMapClient(String systemName)
  {
    SqlMapClient sqlMapClient = null;
    if ((systemName == null) || (systemName.equals(""))) {
      systemName = "default";
    }
    if (this.sqlMapClientPool.containsKey(systemName))
    {
      sqlMapClient = (SqlMapClient)this.sqlMapClientPool.get(systemName);
    }
    else
    {
      sqlMapClient = buildSqlMapClient(systemName);
      this.sqlMapClientPool.put(systemName, sqlMapClient);
    }
    return sqlMapClient;
  }
  
  private SqlMapClient buildSqlMapClient(String systemName)
  {
    String configFileName = "";
    if ((systemName == null) || (systemName.endsWith("default"))) {
      configFileName = "config/ibatis/sql-map-config.xml";
    } else {
      configFileName = "config/ibatis/sql-map-config-" + systemName + ".xml";
    }
    log.info("configFileName=" + configFileName);
    SqlMapClient sqlMapClient = null;
    try
    {
      Reader reader = 
        Resources.getResourceAsReader(configFileName);
      sqlMapClient = 
        SqlMapClientBuilder.buildSqlMapClient(reader);
      log.debug("创建系统" + systemName + "的SqlMapClient成功！");
    }
    catch (IOException ex)
    {
      log.error("创建系统" + systemName + "的SqlMapClient失败！");
      log.error(ex);
    }
    return sqlMapClient;
  }
  
  private static DBClient dbConnect = new DBClient();
}
